<template>
  <el-container style="height: 100%">
    <el-header height="350px">
      <el-table :data="tableData" highlight-current-row stripe @current-change="loadDetail" height="100%">
        <el-table-column
          v-for="column in tableColumns"
          :key="column.code"
          :prop="column.code"
          :label="column.name"
          :width="column.width ? column.width : 100"
          :formatter="
            (row, column, cellValue, index) => {
              return cell_formatter(column, cellValue, tableColumns)
            }
          "
        />
        <el-table-column width="100" label="操作">
          <template #default="scope">
            <el-dropdown>
              <el-button size="small">
                菜单<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="!get_codeable(scope.row)" @click="build(scope.row)">建码</el-dropdown-item>
                  <el-dropdown-item :disabled="!get_qc_status(scope.row)" @click="to_qc(scope.row)">报检</el-dropdown-item>
                  <el-dropdown-item :disabled="get_stin_qty(scope.row) === 0" @click="to_stock_in(scope.row)">入库</el-dropdown-item>
                  <el-dropdown-item :disabled="get_re_qty(scope.row) === 0" @click="to_special(scope.row)">特采</el-dropdown-item>
                  <el-dropdown-item :disabled="get_re_qty(scope.row) === 0" @click="to_return(scope.row)">退货</el-dropdown-item>
                  <el-dropdown-item :disabled="!get_move_status(scope.row)" @click="show_move = true">订货位</el-dropdown-item>
                  <el-dropdown-item @click="printorder(scope.row)">打印</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-header>
    <el-main>
      <el-table :data="currentDetail" stripe height="100%">
        <el-table-column
          v-for="column in qrcode_define"
          :key="column.code"
          :prop="column.code"
          :label="column.name"
          :width="column.width ? column.width : 100"
          :formatter="
            (row, column, cellValue, index) => {
              return cell_formatter(column, cellValue, qrcode_define)
            }
          "
        />
        <el-table-column width="120" label="操作">
          <template #default="scope">
            <el-button size="small" @click="print(scope.row)"> 打印条码 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog v-model="show_cal_panel" title="生成">
      <span style="margin-right: 10px">选择版本：</span>
      <el-select v-model="currentStoragePolicyId" placeholder="政策" @change="changePolicy">
        <el-option v-for="item in currentMaterial?.storage_policy" :key="item.id" :label="item.id" :value="item.id"> </el-option>
      </el-select>
      <el-divider></el-divider>
      <el-descriptions :border="true" style="margin-top: 10px" title="策略信息">
        <el-descriptions-item label="版本号">{{ currentSP?.version }}</el-descriptions-item>
        <el-descriptions-item label="管理模式">{{ currentSP?.ctrl_method_name }}</el-descriptions-item>
        <el-descriptions-item label="每码数量">
          <el-input-number
            v-if="currentSP?.ctrl_method === e_code_ctrl_method.不定数量"
            @change="cal_SP1"
            v-model="unit_qty"
            :min="1"
            :max="currentSP?.codeable"
            :step="1"
          ></el-input-number>
          <span v-else>{{ unit_qty }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="长"
          ><el-input-number v-if="currentSP" :controls="false" v-model="currentSP.l"></el-input-number
        ></el-descriptions-item>
        <el-descriptions-item label="宽"
          ><el-input-number v-if="currentSP" :controls="false" v-model="currentSP.w"></el-input-number
        ></el-descriptions-item>
        <el-descriptions-item label="高"
          ><el-input-number v-if="currentSP" :controls="false" v-model="currentSP.h"></el-input-number
        ></el-descriptions-item>
        <el-descriptions-item label="物料数">{{ currentSP?.codeable }}</el-descriptions-item>
        <el-descriptions-item label="条码数">
          <el-input-number
            v-if="currentSP?.ctrl_method === e_code_ctrl_method.不定数量"
            @change="cal_SP2"
            v-model="code_count"
            :min="0"
            :max="currentSP?.max_code_count"
            :step="1"
          ></el-input-number>
          <span v-else>{{ code_count }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="尾数">{{ currentSP?.remainder }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" :disabled="currentSP?.code_count === 0" @click="confirm"> 生成 </el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="show_move" title="订货位">
      <el-select v-model="move_info.v" @clear="move_info.n = true" @change="move_info.n = false" clearable placeholder="请选择">
        <el-option
          v-for="item in dbStore.move.filter((r) => r.status === e_move_status.开立)"
          :key="item.billcode"
          :label="item.billcode + '|' + item.staff + '|' + item.location.code"
          :value="item.billcode"
        >
        </el-option>
      </el-select>
      <el-divider content-position="left">如果没有对应任务单可以创建一个新的</el-divider>
      <el-select :disabled="!move_info.n" v-model="move_info.s" placeholder="选择工人">
        <el-option v-for="item in dbStore.staff" :key="item" :label="item" :value="item"> </el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <el-select :disabled="!move_info.n" v-model="move_info.l" placeholder="选择库位">
        <el-option v-for="item in dbStore.location" :key="item.code" :label="item.code + '|' + item.zone" :value="item.code">
        </el-option>
      </el-select>
      <template #footer>
        <el-button type="primary" @click="make_move">确认</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script lang="ts" setup>
import { qrcode_define, arrive_bill_define, move_bill_detail_define } from '@/meta/index'
import type { arrive_bill, move_bill, move_bill_detail } from '@/types/billdata'
import { fill_ref_info, cell_formatter, make_billcode, today } from '@/utils/common'
import { onMounted, ref } from 'vue'
import type { pd_qrcode, t_arrive_option } from '@/types/producedata'
import copy from 'copy-to-clipboard'
import { ElMessageBox } from 'element-plus'
import type { bd_material } from '@/types/basedata'
import { e_code_ctrl_method, e_code_prefix, e_material_storage_status, e_move_status, e_qc_status } from '@/types/enum'
import { bill_to_qrcode } from '@/utils/converter'
import { useDbStore } from '@/stores/modules/database'
import { useRouter } from 'vue-router'
import { reserv_from_arrive_to_stock } from '@/utils/reservHelper'
const dbStore = useDbStore()
const move_info = ref<{ s: string; l: string; v: string; n: boolean }>({ s: '', l: '', v: '', n: true })
const code_count = ref<number>()
const unit_qty = ref<number>()
const currentStoragePolicyId = ref<string>()
const currentSP = ref<t_arrive_option>()
const currentMaterial = ref<bd_material>()
const currentArrive = ref<arrive_bill>()
const show_cal_panel = ref<boolean>(false)
const currentDetail = ref<pd_qrcode[]>()
const tableColumns = arrive_bill_define
const tableData = ref<arrive_bill[]>()
const route = useRouter()
const show_move = ref<boolean>(false)
const loadDetail = (val: arrive_bill) => {
  currentArrive.value = val
  const tmp = dbStore.qrcode.filter((r) => r.arrive_bill === val.billcode)
  fill_ref_info(tmp, qrcode_define)
    .then(() => {
      currentDetail.value = tmp
    })
    .catch(() => {
      console.log('err')
    })
}
onMounted(() => {
  const tmp = dbStore.arrive
  fill_ref_info(tmp, arrive_bill_define)
    .then(() => {
      tableData.value = tmp
      loadDetail(tmp[0])
    })
    .catch(() => {
      console.log('err')
    })
})
const print = (p: pd_qrcode) => {
  copy(e_code_prefix.物码 + p.qrcode)
  p.print_count += 1
  dbStore.saveQrCode(dbStore.qrcode)
  ElMessageBox.alert('条码号已复制到剪切板', '提示')
}
const printorder = (p: arrive_bill) => {
  copy(p.billtype + '#' + p.billcode)
  ElMessageBox.alert('条码号已复制到剪切板', '提示')
}
const get_re_qty = (p: arrive_bill) => {
  return p.unqualified - p.return_qty - p.special_qty
}
const get_stin_qty = (p: arrive_bill) => {
  const c = Math.min(p.code_qty, p.qualified + p.special_qty) - p.stockin_qty
  return c
}
const get_codeable = (p: arrive_bill) => {
  return (
    p.code_qty < p.arrive_qty &&
    ((p.code_after_qc && p.status >= e_qc_status.部分完检) || (!p.code_after_qc && p.status === e_qc_status.未报检))
  )
}
const get_move_and_qrcode = (p: arrive_bill) => {
  const all_move: move_bill_detail[] = []
  const all_qrcode = dbStore.qrcode.filter((r) => r.arrive_bill === p.billcode)
  dbStore.move.forEach((r) =>
    r.items.forEach((s) => {
      if (typeof s.arrive_bill === 'string' ? s.arrive_bill : s.arrive_bill.billcode === p.billcode) all_move.push(s)
    })
  )
  return { qrcode: all_qrcode, move: all_move }
}
const get_move_status = (p: arrive_bill) => {
  const { qrcode, move } = get_move_and_qrcode(p)
  return qrcode.length > move.length
}
const get_qc_status = (p: arrive_bill) => {
  return ((!p.code_after_qc && p.code_qty > 0) || p.code_after_qc) && p.status === e_qc_status.未报检
}
const build = (p: arrive_bill) => {
  currentArrive.value = p
  currentStoragePolicyId.value = typeof p.storage_policy === 'string' ? p.storage_policy : p.storage_policy.id
  show_cal_panel.value = true
  if (typeof p.material === 'string') {
    currentMaterial.value = dbStore.material.find((r) => r.code === p.material)
  } else {
    currentMaterial.value = p.material
  }
  changePolicy(currentStoragePolicyId.value)
}
const to_qc = (p: arrive_bill) => {
  currentArrive.value = p
  if (!currentArrive.value.code_after_qc && currentArrive.value.code_qty < currentArrive.value.arrive_qty) {
    ElMessageBox.alert('请先创建条码再报检', '提示')
    return
  }
  currentArrive.value.status = e_qc_status.报检
  dbStore.saveArriveCode()
  dbStore.qrcode
    .filter((r) => r.arrive_bill === currentArrive.value!.billcode)
    .forEach((r) => (r.status = e_material_storage_status.报检))
  dbStore.saveQrCode()
  ElMessageBox.alert('报检成功', '提示')
}
const to_stock_in = (p: arrive_bill) => {
  currentArrive.value = p
  const qty = get_stin_qty(p)
  p.stockin_qty += qty
  dbStore.setMaterialStock(typeof p.material === 'string' ? p.material : p.material.code, qty)
  dbStore.saveArriveCode()
  reserv_from_arrive_to_stock(currentArrive!.value, qty)
}
const to_special = (p: arrive_bill) => {
  currentArrive.value = p
  p.special_qty += get_re_qty(p)
  dbStore.saveArriveCode()
  dbStore.qrcode
    .filter((r) => r.status === e_material_storage_status.冻结)
    .forEach((r) => {
      r.status = e_material_storage_status.特采
    })
  dbStore.saveQrCode()
}
const to_return = (p: arrive_bill) => {
  currentArrive.value = p
  p.return_qty += get_re_qty(p)
  dbStore.saveArriveCode()
  dbStore.qrcode
    .filter((r) => r.status === e_material_storage_status.冻结)
    .forEach((r) => {
      r.status = e_material_storage_status.作废
    })
  dbStore.saveQrCode()
}
const changePolicy = (p: string) => {
  currentArrive.value!.storage_policy = p
  const tmp_sp = currentMaterial.value?.storage_policy.find((r) => r.id === currentStoragePolicyId.value)
  const uncode_qty =
    (currentArrive.value?.code_after_qc
      ? currentArrive.value!.qualified + currentArrive.value!.special_qty
      : currentArrive.value!.arrive_qty) - currentArrive.value!.code_qty
  currentSP.value = {
    material: currentArrive.value!.material,
    billcode: currentArrive.value!.billcode,
    batchcode: currentArrive.value!.billcode,
    ctrl_method: tmp_sp!.ctrl_method,
    ctrl_method_name: e_code_ctrl_method[tmp_sp!.ctrl_method],
    version: tmp_sp!.version,
    max_unit_qty: tmp_sp!.unit_qty,
    unit_qty: tmp_sp!.unit_qty,
    codeable: uncode_qty,
    max_code_count: Math.floor(uncode_qty / tmp_sp!.unit_qty),
    code_count: Math.floor(uncode_qty / tmp_sp!.unit_qty),
    remainder: uncode_qty - tmp_sp!.unit_qty * Math.floor(uncode_qty / tmp_sp!.unit_qty),
    l: currentMaterial.value?.l!,
    h: currentMaterial.value?.h!,
    w: currentMaterial.value?.w!
  }
  code_count.value = Math.floor(uncode_qty / tmp_sp!.unit_qty)
  unit_qty.value = tmp_sp!.unit_qty
}
const cal_SP1 = () => {
  //每码
  const uncode_qty = currentSP.value!.codeable
  currentSP.value!.unit_qty = unit_qty.value!
  const max_count = Math.floor(uncode_qty / currentSP.value!.unit_qty)
  code_count.value = max_count
  currentSP.value!.max_code_count = max_count
  currentSP.value!.code_count = max_count
  currentSP.value!.remainder = currentSP.value!.codeable - currentSP.value!.code_count * currentSP.value!.unit_qty
}
const cal_SP2 = () => {
  //码数
  currentSP.value!.code_count = code_count.value!
  currentSP.value!.remainder = currentSP.value!.codeable - currentSP.value!.code_count * currentSP.value!.unit_qty
}
const confirm = () => {
  const result = bill_to_qrcode(currentSP.value!)
  currentArrive.value!.code_qty += currentSP.value!.code_count * currentSP.value!.unit_qty
  result.forEach((r) => {
    r.status = currentArrive!.value!.status >= e_qc_status.部分完检 ? e_material_storage_status.合格 : e_material_storage_status.收货
    dbStore.addQrCode(r)
  })
  dbStore.saveArriveCode()
  show_cal_panel.value = false
  loadDetail(currentArrive.value!)
}
const make_move = () => {
  if (move_info.value.n) {
    if (!move_info.value.s) {
      ElMessageBox.alert('需要指定工人', '错误')
      return
    }
    if (!move_info.value.l) {
      ElMessageBox.alert('需要指定库位', '错误')
      return
    }
    const move: move_bill = {
      billcode: make_billcode('MV'),
      docdate: today(),
      status: e_move_status.开立,
      staff: move_info.value.s,
      location: dbStore.location.find((r) => r.code === move_info.value.l)!,
      items: []
    }
    currentDetail.value!.forEach((r) => {
      move.items.push({
        arrive_bill: currentArrive.value!,
        qrcode: r,
        material: r.material
      })
    })
    dbStore.addMoveBill(move)
    show_move.value = false
  } else {
    const s = dbStore.move.find((r) => r.billcode === move_info.value.v)!
    currentDetail
      .value!.filter((r) => s.items.map((t) => (typeof t.qrcode === 'string' ? t.qrcode : t.qrcode.qrcode)).indexOf(r.qrcode) < 0)
      .forEach((t) =>
        s.items.push({
          arrive_bill: currentArrive.value!,
          qrcode: t,
          material: t.material
        })
      )
    show_move.value = false
  }
}
</script>
